package demo.application;

import demo.common.MqException;
import demo.mqclient.Channel;
import demo.mqclient.Connection;
import demo.mqclient.ConnectionFactory;
import demo.mqserver.core.BasicProperties;
import demo.mqserver.core.ExchangeType;

import java.io.IOException;

//表示一个消费者
//通常是一个单独的服务器程序
public class Consumer {

    public static void main(String[] args) throws IOException, MqException, InterruptedException {
        System.out.println("启动消费者!");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(9090);

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare("testExchange", ExchangeType.DIRECT, true, false, null);
        channel.queueDeclare("testQueue", true, false, false, null);

        channel.basicConsume("testQueue", true, new demo.common.Consumer() {
            @Override
            public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                System.out.println("[消费数据] 开始!");
                System.out.println("consumerTag = " + consumerTag);
                System.out.println("basicProperties = " + basicProperties);
                String bodyString = new String(body, 0, body.length);
                System.out.println("body = " + bodyString);
                System.out.println("[消费数据] 结束!");
            }
        });

        //由于消费者也不知道生产者要生产多少,这里通过循环模拟一直等待消费
        while(true){
            Thread.sleep(1000);
        }
    }
}
